<?php

namespace app\shop\controller\api;

use app\ApiController;
use app\shop\model\SlideModel;
use app\shop\model\GoodsModel;
use app\shop\model\NavMenuModel;
use think\Db;
use think\Exception;
use wangdiantong\Wdtwms;

class Yuque extends ApiController
{
    /**
     * 商品同步接口
     * http://39.105.14.222/wms_api/wdt_service.php
     * app_key: wdt15965888142181
     * app_secret: a3ebda796851fbdbf075f395b6dfac90
     */
    public function wdt($info)
    {
        $wdt = new Wdtwms();
        $content = array(
            'actionType' => 'add',
            'warehouseCode' => $info['goods_id'],
            'item' => array('itemCode' => $info['goods_id'],
                'itemName' => $info['goods_name'],
                'barCode' => $info['goods_id'],
                'itemType' => 'ZC')
        );
//        $content = json_encode($content);
        $result = $wdt->wdt_api($content, 'WDT_WMS_SINGLEITEM_SYNCHRONIZE');

        if ($result['flag'] == 'success') {
            $status = 1;
        } else {
            $status = 0;
        }
        $insert = array(
            'order_id' => $info['goods_id'],
            'type' => 1,
            'content' => json_encode($result, JSON_UNESCAPED_UNICODE),
            'param' => json_encode($content, JSON_UNESCAPED_UNICODE),
            'kd_api_id' => 1,
            'add_time' => time(),
            'status' => $status,
        );
        logisticsApiLog($insert);
//        var_dump($result);
//        die;
    }

    /**
     *查询商品
     */
    public function selectGoods($goods_id)
    {
        $where['goods_id'] = $goods_id;
        $goods_info = Db::name('shop_goods')->where($where)->find();
        $wdt = new Wdtwms();
        $content = array(
            'itemCode' => $goods_id,
        );
        $result = $wdt->wdt_api($content, 'WDT_WMS_SINGLEITEM_QUERY');
        if ($result['flag'] == 'success') {
            //查到商品

        } else {
            //未查到商品(入库商品)
            $this->wdt($goods_info);

        }
//        var_dump($result);
    }


    /**
     * 发货单创建接口(商城订单)
     */
    public function sendCreateAdd($order_id)
    {
        try {
            $order_info = Db::name('shop_order_info')->where(array('order_id' => $order_id))->find();
            $shop_goods_warehouse = Db::name('shop_goods_warehouse')->where(array('id' => $order_info['warehouse_id']))->find();
            $shop_goods_warehouse['province'] = Db::name('main_region')->where(array('id' => $shop_goods_warehouse['province']))->find()['name'];
            $shop_goods_warehouse['city'] = Db::name('main_region')->where(array('id' => $shop_goods_warehouse['city']))->find()['name'];
            $shop_goods_warehouse['district'] = Db::name('main_region')->where(array('id' => $shop_goods_warehouse['district']))->find()['name'];
            $order_info_address = explode(',', $order_info['merger_name']);
            //获取发货数量
            $data_order_goods = Db::name('shop_order_goods')->where(array('order_id' => $order_info['order_id'], 'after_sale_num' => 0))->select();
            $data_array = array();
            foreach ($data_order_goods as $k => $v) {
                $data_array[$k] = array(//订单列表
                    'orderLineNo' => $v['rec_id'],
                    'key' => 'orderLine',
                    'itemCode' => $v['goods_id'],//商家编码
                    'actualPrice' => $v['sale_price'] * $v['goods_number'],//实际成交价
                    'planQty' => $v['goods_number'],//应发商品数量
                );
            }
            $wdt = new Wdtwms();
            $content = array(
                'deliveryOrder' => array( //发货单信息
                    'deliveryOrderCode' => $order_info['order_sn'],//出库单号(订单号)
                    'orderType' => 'JYCK',//出库单类型(JYCK=一般交易出库单;HHCK=换货出库单;BFCK=补发出库单;)
                    'warehouseCode' => $order_info['warehouse_id'],//仓库编码
                    'createTime' => date('Y-m-d H:i:s'),//发货单创建时间 (YYYY-MM-DD HH:MM:SS)
                    'placeOrderTime' => date('Y-m-d H:i:s', $order_info['pay_time']),//前台订单/                店铺订单的创建时间/                下单时间
                    'operateTime' => date('Y-m-d H:i:s'),//操作(审核)时间           (YYYY-MM-DD HH:MM:SS)
                    'shopNick' => '修品享购',//店铺名称
                    'logisticsCode' => 'OTHER',//物流公司编码，对应wms仓库物流映射的“oms物流编码”
                    'senderInfo' => array(
                        'name' => $shop_goods_warehouse['f_name'],//发货姓名
                        'mobile' => $shop_goods_warehouse['tel'],//移动电话
                        'province' => $shop_goods_warehouse['province'],//省份
                        'city' => $shop_goods_warehouse['city'],//城市
                        'area' => $shop_goods_warehouse['district'],//区域(不必填)
                        'detailAddress' => $shop_goods_warehouse['address'],//详细地址
                    ),
                    'receiverInfo' => array(
                        'name' => $order_info['consignee'],//收货姓名
                        'mobile' => $order_info['mobile'],//移动电话
                        'province' => $order_info_address[0],//省
                        'city' => $order_info_address[1],//市
                        'area' => $order_info_address[2],//区域(不必填)
                        'detailAddress' => $order_info['address'],//详细地址
                    ),
                ),
                'orderLines' => $data_array
            );
//        var_dump($content['orderLines']);die;
            $result = $wdt->wdt_api($content, 'WDT_WMS_DELIVERYORDER_CREATE');
            if ($result['flag'] == 'success') {
                $status = 1;
            } else {
                $status = 0;

            }
            $insert = array(
                'order_id' => $order_id,
                'type' => 2,
                'content' => json_encode($result, JSON_UNESCAPED_UNICODE),
                'param' => json_encode($content, JSON_UNESCAPED_UNICODE),
                'kd_api_id' => 1,
                'add_time' => time(),
                'status' => $status,
            );
            logisticsApiLog($insert);
            return $result;
        } catch (Exception $e) {
            $insert = array(
                'order_id' => $order_id,
                'type' => 1,
                'content' => $e->getMessage(),
                'add_time' => time(),
            );
            logisticsApiLogError($insert);
            return false;
        }

    }


    /**
     *  发货单创建接口(代理商提货)
     */
    public function sendCreateAgentAdd($order_id)
    {
        try {
            $order_info = Db::name('channel_order_info')->where(array('order_id' => $order_id))->find();
            $shop_goods_warehouse = Db::name('shop_goods_warehouse')->where(array('id' => $order_info['warehouse_id']))->find();
            $shop_goods_warehouse['province'] = Db::name('main_region')->where(array('id' => $shop_goods_warehouse['province']))->find()['name'];
            $shop_goods_warehouse['city'] = Db::name('main_region')->where(array('id' => $shop_goods_warehouse['city']))->find()['name'];
            $shop_goods_warehouse['district'] = Db::name('main_region')->where(array('id' => $shop_goods_warehouse['district']))->find()['name'];
            $order_info_address = explode(',', $order_info['merger_name']);
            //获取发货数量
            $data_order_goods = Db::name('channel_order_goods')->where(array('order_id' => $order_info['order_id']))->select();
            $data_array = array();
            foreach ($data_order_goods as $k => $v) {
                $data_array[$k] = array(//订单列表
                    'orderLineNo' => $v['rec_id'],
                    'key' => 'orderLine',
                    'itemCode' => $v['goods_id'],//商家编码
                    'actualPrice' => $v['sale_price'] * $v['goods_number'],//实际成交价
                    'planQty' => $v['goods_number'],//应发商品数量
                );
            }
            $wdt = new Wdtwms();
            $content = array(
                'deliveryOrder' => array( //发货单信息
                    'deliveryOrderCode' => $order_info['order_sn'],//出库单号(订单号)
                    'orderType' => 'JYCK',//出库单类型(JYCK=一般交易出库单;HHCK=换货出库单;BFCK=补发出库单;)
                    'warehouseCode' => $order_info['warehouse_id'],//仓库编码
                    'createTime' => date('Y-m-d H:i:s'),//发货单创建时间 (YYYY-MM-DD HH:MM:SS)
                    'placeOrderTime' => date('Y-m-d H:i:s', $order_info['pay_time']),//前台订单/                店铺订单的创建时间/                下单时间
                    'operateTime' => date('Y-m-d H:i:s'),//操作(审核)时间           (YYYY-MM-DD HH:MM:SS)
                    'shopNick' => '修品享购',//店铺名称
                    'logisticsCode' => 'OTHER',//物流公司编码，对应wms仓库物流映射的“oms物流编码”
                    'senderInfo' => array(
                        'name' => $shop_goods_warehouse['f_name'],//发货姓名
                        'mobile' => $shop_goods_warehouse['tel'],//移动电话
                        'province' => $shop_goods_warehouse['province'],//省份
                        'city' => $shop_goods_warehouse['city'],//城市
                        'area' => $shop_goods_warehouse['district'],//区域(不必填)
                        'detailAddress' => $shop_goods_warehouse['address'],//详细地址
                    ),
                    'receiverInfo' => array(
                        'name' => $order_info['consignee'],//收货姓名
                        'mobile' => $order_info['mobile'],//移动电话
                        'province' => $order_info_address[0],//省
                        'city' => $order_info_address[1],//市
                        'area' => $order_info_address[2],//区域(不必填)
                        'detailAddress' => $order_info['address'],//详细地址
                    ),
                ),
                'orderLines' => $data_array
            );
            $result = $wdt->wdt_api($content, 'WDT_WMS_DELIVERYORDER_CREATE');
            if ($result['flag'] == 'success') {
                $status = 1;
            } else {
                $status = 0;
            }
            $insert = array(
                'order_id' => $order_id,
                'type' => 2,
                'log_type' => 1,//记录类型;0-商城订单;1-提货订单
                'content' => json_encode($result, JSON_UNESCAPED_UNICODE),
                'param' => json_encode($content, JSON_UNESCAPED_UNICODE),
                'kd_api_id' => 1,
                'add_time' => time(),
                'status' => $status,
            );
            logisticsApiLog($insert);
            return $result;

        } catch (Exception $e) {
            $insert = array(
                'order_id' => $order_id,
                'type' => 2,
                'content' => $e->getMessage(),
                'add_time' => time(),
            );
            logisticsApiLogError($insert);
            return false;
        }

    }


    /**
     * 入库单创建接口
     * goods_number  入库数量
     * type  更新入库数量;1-更新输入数量和同步商品
     */
    public function inCrateAdd($data, $type = 0)
    {
        $where['goods_id'] = $data['goods_id'];
        $goods_info = Db::name('shop_goods')->where($where)->find();
        if ($data['goods_number'] > 0) {
            $wdt = new Wdtwms();
            $content = array(
                'entryOrder' => array(
                    'entryOrderCode' => time().$goods_info['goods_id'],//入库单号
                    'warehouseCode' => $goods_info['warehouse_id'],//仓库编码(可以写空)
                    'orderType' => 'QTRK',//业务类型(CGRK=采购入库;DBRK=调拨入库;QTRK=其他入库;B2BRK=B2B入库;SCRK=生产入库;只传英文编码)
                ),
                'orderLines' => array(
                    'orderLine' => array(
                        'itemCode' => $goods_info['goods_id'],//商家编码
                        'planQty' => $data['goods_number'],//应收商品数量(入库数量)
                    )
                )
            );
            $result = $wdt->wdt_api($content, 'WDT_WMS_ENTRYORDER_CREATE');
            if ($result['flag'] == 'success') {
                $status = 1;
            } else {
                $status = 0;
            }
            $insert = array(
                'order_id' => $data['goods_id'],
                'type' => 3,
                'content' => json_encode($result, JSON_UNESCAPED_UNICODE),
                'param' => json_encode($content, JSON_UNESCAPED_UNICODE),
                'kd_api_id' => 1,
                'add_time' => time(),
                'status' => $status,
            );
            logisticsApiLog($insert);
        }

    }

    /**
     * 批量插入库存
     */
    public function batchStock(){

        $data_info=Db::name('shop_goods')->where(array('warehouse_id'=>1))->select();
        foreach ($data_info as $k=>$v){
            $this->inCrateAdd(array('goods_id'=>$v['goods_id'],'goods_number'=>$v['goods_number']));
        }
        echo "执行成功";
    }

    /**
     * 出库单创建接口
     */
    public function outCreateAdd($order_id)
    {
        $where['order_id'] = $order_id;
        $where['after_sale_num'] = 0;
        $order_goods = Db::name('shop_order_goods')->where($where)->select();

        $wdt = new Wdtwms();
        foreach ($order_goods as $k => $v) {
            $content = array(
                'deliveryOrder' => array(
                    'deliveryOrderCode' => time(),//出库单号
                    'orderType' => 'PTCK',//出库单类型(PTCK=普通出库单;DBCK=调拨出库;B2BCK=B2B出库;QTCK=其他出库;CGTH=采购退货出库单;SCCK=生产出库,唯品出库使用B2B出库)
                    'warehouseCode' => '1',
                    'createTime' => date('Y-m-d H:i:s')
                ),
                'orderLines' => array(
                    'orderLine' => array(
                        'itemCode' => $v['goods_id'],//商家编码
                        'planQty' => $v['goods_number'],//发货数量
                    )
                )
            );
            $result = $wdt->wdt_api($content, 'WDT_WMS_STOCKOUT_CREATE');
            if ($result['flag'] == 'success') {
                echo "出库成功";

            } else {
                echo "出库失败";
            }
        }

    }

    /**
     * 发货回调地址
     */
    public function wdt_notify()
    {
        $post = request()->get();
        $postStr = file_get_contents("php://input");
        $document = $_SERVER['DOCUMENT_ROOT'];
        $wdt = new Wdtwms();
        switch ($post['method']) {
            case 'WDT_WMS_ENTRYORDER_CONFIRM': //入库回调
                $filname = $document . '/log/' . 'log_' . date('Y-m-d') . 'in_wdt.txt';
                file_put_contents($filname, date("Y-m-d H:i:s") . "\r\n" . print_r($post, true) . "\r\n" . $postStr . "\r\n\n\n\n", FILE_APPEND);
                $result = array(
                    'flag' => 'success',
                    'code' => 0,
                    'message' => '成功确认入库单'
                );
                $result = $wdt->arr_to_xml($result);
                break;
            case 'WDT_WMS_STOCKOUT_CONFIRM': //出库单确认接口
                $filname = $document . '/log/' . 'log_' . date('Y-m-d') . 'out_wdt.txt';
                file_put_contents($filname, date("Y-m-d H:i:s") . "\r\n" . print_r($post, true) . "\r\n" . $postStr . "\r\n\n\n\n", FILE_APPEND);
                $result = array(
                    'flag' => 'success',
                    'code' => 0,
                    'message' => 'success'
                );
                $result = $wdt->arr_to_xml($result);
                break;
            case 'WDT_WMS_DELIVERYORDER_CONFIRM'://发货确认接口
                $result = array(
                    'flag' => 'success',
                    'code' => 0,
                    'message' => 'success'
                );
                $result = $wdt->arr_to_xml($result);
                $order_sn = $result['deliveryOrder']['deliveryOrderCode'];//商城订单编号
                $logistics = $result['packages']['package'];
                $logisticsCode = $logistics['logisticsCode'];//快递编码
                $expressCode = $logistics['expressCode'];//物流单号
                $packageCode = $logistics['packageCode'];//包裹编号
                $order_type = substr($order_sn, 0, 2);
                $update['invoice_no'] = $expressCode;
                $update['packageCode'] = $packageCode;
                $update['update_time'] = time();
                if ($order_type == 'ws') {
                    $filname = $document . '/log/' . 'log_' . date('Y-m-d') . 'send_wdt_t.txt';
                    file_put_contents($filname, date("Y-m-d H:i:s") . "\r\n" . print_r($post, true) . "\r\n" . $postStr . "\r\n\n\n\n", FILE_APPEND);
                    //提货
                    Db::name('channel_order_info')->where(array('order_sn' => $order_sn))->update($update);
                } else {
                    $filname = $document . '/log/' . 'log_' . date('Y-m-d') . 'send_wdt.txt';
                    file_put_contents($filname, date("Y-m-d H:i:s") . "\r\n" . print_r($post, true) . "\r\n" . $postStr . "\r\n\n\n\n", FILE_APPEND);

                    //更新商城订单运单号码
                    Db::name('shop_order_info')->where(array('order_sn' => $order_sn))->update($update);

                }


                break;

            default:
                $result = "回传地址";
        }
        echo $result;
        die;

    }

}
